<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <el-form :model="queryParams" ref="queryForm" :inline="true"  v-show="showSearch" label-width="80px">
          <el-form-item label="服务商" prop="ispName">
            <el-input v-model="queryParams.ispName" placeholder="请输入服务商" size="small" clearable style="width: 150px"/>
          </el-form-item>
          <el-form-item label="渠道名称" prop="channelName">
            <el-input v-model="queryParams.channelName" placeholder="请输入渠道名称" size="small" clearable style="width: 150px"/>
          </el-form-item>
          <el-form-item label="渠道状态" prop="statusCode">
            <el-select @change="handleQuery" v-model="queryParams.statusCode" size="small" clearable style="width: 150px" placeholder="请选择">
              <el-option key="" label="全部" value=""/>
              <el-option
                v-for="item in statusCodeList"
                :key="item.dictCode"
                :label="item.dictName"
                :value="item.dictCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary"  v-hasPermi="['saveSmsChannel']"  icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" v-hasPermi="['updateSmsChannel']"  icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" v-hasPermi="['deleteSmsChannel']"  icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete">删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="querySmsChannelPageResList" :columns="columns"></right-toolbar>
        </el-row>
        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
                    @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column type="selection" align="center"/>
          <el-table-column label="渠道名称" align="left" prop="channelName"/>
          <el-table-column label="渠道编码" align="left" prop="channelCode"/>
          <el-table-column label="渠道状态" align="center" prop="statusName" width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.statusColor">{{scope.row.statusName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建部门" align="left" prop="createDeptName"/>
          <el-table-column label="服务商名" align="left" prop="ispName"/>
          <el-table-column label="服务商状态" align="center" prop="ispStatusName" width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.ispStatusColor">{{scope.row.ispStatusName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" sortable='custom' width="200" />
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['updateSmsChannel']" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" v-hasPermi="['deleteSmsChannel']" icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0"  :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows" @pagination="querySmsChannelPageResList"/>
      </el-col>
    </el-row>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="94px">

        <el-form-item label="服务商" prop="ispId" v-if="form.channelId === undefined" >
          <el-select :hide-required-asterisk="true" v-model="form.ispId"  @change="handleSmsIspChange" placeholder="请选择服务商,确定后禁止修改!"  style="width: 100%;">
            <el-option
              v-for="(item,i) in ispResList"
              :key="item.ispId"
              :label="item.ispName"
              :value="item.ispId"
            />
          </el-select>
        </el-form-item>

        <el-form-item  v-if="form.channelId !== undefined" label="服务商" prop="ispName">
          <el-input disabled v-model="form.ispName"/>
        </el-form-item>

        <el-form-item label="渠道名称" prop="channelName">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.channelName" placeholder="请输入渠道名称" maxlength="20" />
        </el-form-item>

        <el-form-item label="渠道状态" prop="statusCode">
          <el-select :hide-required-asterisk="true" v-model="form.statusCode" clearable placeholder="请选择状态"  style="width: 100%;">
            <el-option
              v-for="item in statusCodeList"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-for="(item,index) in form.ispAttributeList" :key="index" :label="item.name"  :prop="'ispAttributeList.' + index + '.value'" :rules="{required: item.required, message: item.requiredMessage, trigger: 'blur'}">
          <el-input  v-if="item.type === 'text'" :hide-required-asterisk="true" autocomplete="off" v-model="item.value" :placeholder="item.desc" :minlength="item.minlength?item.minlength:0"  :maxlength="item.maxlength?item.maxlength:20" />
        </el-form-item>
      </el-form>


      <el-descriptions v-if="ispTips" :colon=false>
        <el-descriptions-item > <el-tag size="small">{{ispTips}}</el-tag></el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {querySmsChannelPageResList, saveSmsChannel, updateSmsChannel, deleteSmsChannelByChannelId, querySmsChannelResByChannelId} from '@/api/sms/smsChannel'
  import {queryNormalSelectSmsIspResList} from '@/api/sms/smsIsp'
  import { getDicListByDictCodeList } from '@/api/common/dict'
  //默认查询参数
  let defaultQueryParams = {
    ispName: undefined,
    startTime: undefined,
    endTime: undefined,
    channelName: undefined,
    statusCode: undefined,
    page: 1,
    rows: 10
  }
  export default {
    name: 'smsChannelAdmin',
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        //操作短信渠道
        dataList: [],
        // 日期范围
        dateRange: [],
        //渠道状态
        statusCodeList: [],
        //服务商list
        ispResList:[],
        // 弹出层标题
        title: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        // 增加修改表单参数
        form: {},
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //列信息
        columns: [],
        //温馨提示
        ispTips:undefined,
        // 新增修改表单校验
        addUpdateOpenRules: {
          channelName: [
            { required: true, message: "渠道名称不能为空",trigger: "blur" },
          ],
          statusCode: [
            { required: true, message: "渠道状态必须选择"}
          ],
          ispId: [
            { required: true, message: "服务商必须选择"},
          ]
        }
      }
    },
    created() {
      this.querySmsChannelPageResList()
      this.initDict()
    },
    methods: {
      // 选择短信服务商事件
      handleSmsIspChange(val) {
        let that = this
        that.$refs['form'].clearValidate();
        this.form.ispAttributeList = []
        if (this.form.ispId) {
          this.ispResList.forEach(function (v, i) {
            if (v.ispId === val) {
              that.ispTips = v.description
              that.form.ispAttributeList = v.ispAttributeList
            }
          });
        }
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.channelId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column) {
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.querySmsChannelPageResList()
      },
      /** 查询短信渠道列表 */
      querySmsChannelPageResList() {
        this.loading = true
        querySmsChannelPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
            this.dataList = res.data.records
            this.total = res.data.total
          }
        ).finally(() => {
          //关闭加载特效
          this.loading = false
        })
      },
      //获取数据字典
      initDict(){
        let dictArr = ["STATUS"];
        getDicListByDictCodeList(dictArr).then(res => {
          this.statusCodeList = JSON.parse(JSON.stringify(res.data['STATUS']));
        });
      },
      //获取服务商
      queryNormalSelectSmsIspResList(){
        queryNormalSelectSmsIspResList({}).then(res => {
          this.ispResList = res.data;
        });
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.queryNormalSelectSmsIspResList();
        this.addUpdateOpen = true;
        this.title = "添加渠道";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.queryNormalSelectSmsIspResList();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        const channelId={channelId:row.channelId}
        querySmsChannelResByChannelId(channelId).then(response => {
          //修改表单填充
          this.form =  response.data;
          this.ispTips = response.data.description;
        })
        this.addUpdateOpen = true;
        this.title = "修改渠道";
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认删除所选渠道?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const channelId={channelId:row.channelId}
          return deleteSmsChannelByChannelId(channelId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.querySmsChannelPageResList();
        }).catch(function() {});
      },

      /** 提交保存或修改按钮 */
      submitForm: function() {
        if (this.form.ispAttributeList){
          //定义一个数组用来存放
          const optionArr = []
          this.form.ispAttributeList.forEach(v => {
            let value = v.value;
            optionArr.push({"value":value?value:'',"key":v.key})
          })
          this.form.channelIspAttribute = JSON.stringify(optionArr);
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.channelId !== undefined) {
              updateSmsChannel(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.querySmsChannelPageResList();
                this.addUpdateOpen = false
              });
            } else {
              saveSmsChannel(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.querySmsChannelPageResList();
                this.addUpdateOpen = false
              });
            }
          }
        });
      },

      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = []
        this.resetForm(fromId)
        this.handleQuery()
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.querySmsChannelPageResList()
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.addUpdateOpen = false
      },
      // 表单重置
      reset() {
        this.ispTips = undefined;
        this.form = {
          ispId: undefined,
          channelName: undefined,
          channelIspAttribute: [],
          remark: undefined,
          sort: 1,
          statusCode: undefined
        };
        this.resetForm('form')
      }
    }
  }
</script>
